package com.mti;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class GiveMeWeatherActivity extends MapActivity implements LocationListener
{
	private LocationManager locationManager;
	private MapView mapView;
	private MapController mapController;
	private MyLocationOverlay overlay;
	private double latitude;
	private double longitude;
	private static CityWeather homeCityWeather = null;

	// TO REMOVE
	private String language;
	private GeoPoint geoPoint;
	
	public static boolean gIsFahrenheit;

	/**
	 * Getter/Setter
	 */
	public static CityWeather getHomeCityWeather() {
		return homeCityWeather;
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /**
         * First we need to retrieve the language of the device
         */
        
        String curLng = Locale.getDefault().getLanguage();
        if (curLng.isEmpty()) {
        	language = "en";
        }
        else {
        	language = curLng.substring(0, 2);
        }
        
        /**
         *  Will retrieve in the "appPreferences" file the display of temperature
         *  If this is the first time we will display in Fahrenheit
         */
        final SharedPreferences sharedPref = getSharedPreferences("appPreferences", 0);
        gIsFahrenheit = sharedPref.getBoolean("isFahrenheit", true);
        /***********************************************/
        
        /// Init du systeme d'onglets
        TabHost tabs= (TabHost)findViewById(R.id.tabhost);

        tabs.setup();
        
        TabSpec tab_home = tabs.newTabSpec("tab_home");
        tab_home.setContent(R.id.tab_home);
        /// Enables us to translate the title of the tabs
        tab_home.setIndicator(getString(R.string.tab_name_home));
        tabs.addTab(tab_home);
        
        TabSpec tab_favorites = tabs.newTabSpec("tab_favorites");
        tab_favorites.setContent(R.id.tab_favorites);
        tab_favorites.setIndicator(getString(R.string.tab_name_favorites));
        tabs.addTab(tab_favorites);
        
        TabSpec tab_settings = tabs.newTabSpec("tab_settings");
        tab_settings.setContent(R.id.tab_settings);
        tab_settings.setIndicator(getString(R.string.tab_name_settings));
        tabs.addTab(tab_settings);
        
        /***********************************************/
        
        // Liste de favoris
        Button addFavorite = (Button) findViewById(R.id.add_to_favorites);
        
        /**
         * Retrieve and display favorites in the list
         */
        
        ListView favoritesListView = (ListView) findViewById(R.id.favorites_list_view);
        String cities = sharedPref.getString("city", "");
        String[] listCities = cities.split(",");

        /**
         * Now favoritesCityWeather is a list with all favorites cities
         * We must now show them in the list
         */
        
        if (listCities == null || listCities.length == 0){
			String[] listeStrings = {"Oops, nothing to show."};
			favoritesListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listeStrings));
        }
        else {
			favoritesListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listCities));
        }

        addFavorite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/**
				 * /!\ /!\ /!\ /!\ WARNING always send <CurrentClass>.this
				 */
		        LayoutInflater factory = LayoutInflater.from(GiveMeWeatherActivity.this);
		        final View alertDialogView = factory.inflate(R.layout.alert_add_favorite, null);

		        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(GiveMeWeatherActivity.this);
		        alertDialogBuilder.setView(alertDialogView);
		        alertDialogBuilder.setTitle(getString(R.string.add_favorite_header));
		        alertDialogBuilder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
		        	public void onClick(DialogInterface dialog, int which) {
		        		/**
		        		 * The city written by the user
		        		 */
		        		EditText editTextWrittenCity = (EditText)alertDialogView.findViewById(R.id.alert_edit);
		        		if (!editTextWrittenCity.getText().toString().isEmpty()) {
			            	/**
			            	 * We take the previous favorites cities and add the new one
			            	 * Our delimitor is a comma (,) so if the city has one, we remove it
			            	 */
		    				String res = sharedPref.getString("city", "") + editTextWrittenCity.getText().toString().replace(",", " ") + ",";
		    				
		            		final SharedPreferences.Editor editor = sharedPref.edit();
		    				editor.putString("city", res);
		    				editor.commit();
		        		}
		        	}
		        });

		        alertDialogBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            // Do nothing as we cancel
		            }
		        });
		        alertDialogBuilder.show();
			}
		});
        /***********************************************/
        
        /**
         * Here we retrieve the user choice if he/she changes
         * how to display the temperature 
         */
        
        RadioGroup radioGroupTemp = (RadioGroup) findViewById(R.id.choice_temp_display);
        
		RadioButton rb1 = (RadioButton) findViewById(R.id.radiobutton_fahrenheit);
		RadioButton rb2 = (RadioButton) findViewById(R.id.radiobutton_celcius);
        
		/**
		 * Which radioButton is checked at the beginning ? We chose Fahrenheit
		 * But watch out! if you wanna change, change the
		 * gIsFahrenheit = sharedPref.getBoolean("isFahrenheit", true);
		 * at the beginning of the activity too into
		 * gIsFahrenheit = sharedPref.getBoolean("isFahrenheit", false);
		 */
		if (!(rb1.isChecked()) && !(rb2.isChecked())) {
			rb1.setChecked(true);
			rb2.setChecked(false);
		}
        
        radioGroupTemp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        	
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				RadioButton rb1 = (RadioButton) findViewById(R.id.radiobutton_fahrenheit);
				
				if (rb1.isChecked()) {
					gIsFahrenheit = true;
				}
				else {
					gIsFahrenheit = false;
				}
				final SharedPreferences.Editor editor = sharedPref.edit();
				editor.putBoolean("isFahrenheit", gIsFahrenheit);
				editor.commit();
			}
		});
        /***********************************************/
        /******************    map    ******************/
        /***********************************************/
        
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);

		//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, this);
		
		mapView = (MapView) findViewById(R.id.mapView);
		mapController = mapView.getController();
		mapController.setZoom(6);
		
		Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (lastKnownLocation != null) {
			onLocationChanged(lastKnownLocation);
		}
		else {
        	Button forecastConditionButton = (Button) findViewById(R.id.forecast_condition);
        	forecastConditionButton.setVisibility(4);
        	mapView.setVisibility(4);
        	
        	TextView windTextView = (TextView) findViewById(R.id.wind_message);
        	TextView windLabel = (TextView) findViewById(R.id.wind_label);
        	LinearLayout tempLayout = (LinearLayout) findViewById(R.id.temp_layout);
        	LinearLayout humLayout = (LinearLayout) findViewById(R.id.hum_layout);
        	
        	windLabel.setVisibility(4);
        	tempLayout.setVisibility(4);
        	humLayout.setVisibility(4);
        	
        	windTextView.setText("The application is not able to find any location");
        }
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

	public void onLocationChanged(Location location) {		
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		geoPoint = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
		mapController.animateTo(geoPoint);
		mapController.setCenter(geoPoint);
		overlay = new MyLocationOverlay(GiveMeWeatherActivity.this, mapView);
		mapView.getOverlays().add(overlay);
		overlay.enableMyLocation();
		
		List<Address> myList = null;
		
        Geocoder myLocation = new Geocoder(GiveMeWeatherActivity.this, Locale.getDefault());
        
        if (myLocation != null) {
	        try {
	        	Button forecastConditionButton = (Button) findViewById(R.id.forecast_condition);
	        	forecastConditionButton.setVisibility(1);
	        	mapView.setVisibility(1);
	        	
	            myList = myLocation.getFromLocation(latitude, longitude, 1);
	            
	            if (myList == null || myList.size() == 0)
	            	throw new Exception("No location found");
	            
	            String locality = myList.get(0).getLocality().toString();
	            
	            ContainerData cd = new ContainerData();
	            
	            try {
					cd.execute(new String[] {locality, language});
				} catch (Exception e1) {
					e1.printStackTrace();
				}
	            
	            try {
	            	homeCityWeather = cd.get().get(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				
				TextView cityTextView = (TextView) findViewById(R.id.city_name);
				ImageView weatherImage = (ImageView) findViewById(R.id.weather_icon);
				TextView conditionTextView = (TextView) findViewById(R.id.meteo_message);
				TextView temperatureTextView = (TextView) findViewById(R.id.temp);
				TextView humidityTextView = (TextView) findViewById(R.id.hygro);
				TextView windTextView = (TextView) findViewById(R.id.wind_message);
				
				cityTextView.setText(homeCityWeather.getCity());
				weatherImage.setImageBitmap(homeCityWeather.getIcon());
				conditionTextView.setText(homeCityWeather.getCondition());
				windTextView.setText(homeCityWeather.getWindCondition());

				if (gIsFahrenheit)
					temperatureTextView.setText(homeCityWeather.getTempF() + "°F");
				else
					temperatureTextView.setText(homeCityWeather.getTempC() + "°C");
				
				humidityTextView.setText(""+homeCityWeather.getHumidity());

	        	TextView windLabel = (TextView) findViewById(R.id.wind_label);
				if (windLabel.getVisibility() == 4) {
		        	LinearLayout tempLayout = (LinearLayout) findViewById(R.id.temp_layout);
		        	LinearLayout humLayout = (LinearLayout) findViewById(R.id.hum_layout);
		        	
		        	windLabel.setVisibility(0);
		        	tempLayout.setVisibility(0);
		        	humLayout.setVisibility(0);
				}
				
	        } catch (IOException e1) {
	            e1.printStackTrace();
	        } catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	public void forecastConditionButton(View view) {
		Intent i = new Intent(GiveMeWeatherActivity.this, ForecastConditionActivity.class);
		startActivity(i);
	}
}